package com.saris.primego.service.impl;

//import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.saris.primego.common.constant.MessageConstant;
import com.saris.primego.common.exception.LoginFailedException;
import com.saris.primego.common.exception.WechatException;
import com.saris.primego.common.properties.WeChatProperties;
import com.saris.primego.common.utils.HttpClientUtil;
import com.saris.primego.dao.UserRepository;
import com.saris.primego.pojo.dto.UserLoginDTO;
import com.saris.primego.pojo.entity.User;
import com.saris.primego.service.UserService;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private final WeChatProperties weChatProperties;
    private final UserRepository userRepository;

    public UserServiceImpl(WeChatProperties weChatProperties, UserRepository userRepository) {
        this.weChatProperties = weChatProperties;
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());

        // 判断openid是否为空，如果为空表示登录失败，抛出异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断当前用户是否新用户
        List<User> users = userRepository.findByOpenid(openid);
        if (!users.isEmpty()) {
            return users.getFirst();
        }
        User user = new User();
        // 如果是新用户，自动完成注册
        user.setOpenid(openid);
        user.setCreateTime(LocalDateTime.now());
        return userRepository.save(user);
    }

    private String getOpenid(String code) {
        // 调用微信接口服务，获得当前微信用户的openid
        Map<String, String> params = Map.of(
                "appid", weChatProperties.getAppid(),
                "secret", weChatProperties.getSecret(),
                "js_code", code,
                "grant_type", "authorization_code"
        );

        String json = HttpClientUtil.doGet(WX_LOGIN, params);

        try {
            // 使用 Fastjson2 解析 JSON 字符串
            JSONObject node = JSON.parseObject(json);

            // 检查是否存在错误码字段
            if (node.containsKey("errcode")) {
                // 提取错误码和错误信息
                String errcode = node.getString("errcode");
                String errmsg = node.getString("errmsg");
                throw new WechatException("微信错误: " + errcode + " - " + errmsg);
            }

            // 安全获取 openid 字段值
            return node.getString("openid");
        } catch (JSONException e) {
            throw new WechatException("解析微信响应失败: "+ e.getMessage());
        }
    }
}
